package com.my.blog.website.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.my.blog.website.config.AlipayConfig;
import com.my.blog.website.modal.Vo.*;
import com.my.blog.website.service.IAlipayService;
import com.my.blog.website.service.IContentService;
import com.my.blog.website.service.IRechargeRecordService;
import com.my.blog.website.utils.AjaxResult;
import com.my.blog.website.utils.TaleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ：gyh
 * @date ：Created in 2020/10/10 22:43
 * @description：支付宝当面付控制器
 * @modified By：gyh
 * @version: 1.0
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController {
    private static final Logger log = LoggerFactory.getLogger(AlipayController.class);

    @Resource
    private AlipayConfig alipayConfig;

    @Resource
    private IRechargeRecordService rechargeRecordService;

    @Resource
    IAlipayService alipayService;

    @Resource
    private IContentService contentService;


    /**
     * @Author: gyh
     * @Description: 生成支付二维码
     * @DateTime: 2020/10/12 0:47
     * @Params: [rechargeRecord, cid, request] 传入相应参数，cid为文章id
     * @Return com.my.blog.website.utils.AjaxResult
     */
    @PostMapping("/precreate")
    @ResponseBody
    public AjaxResult getPayQrcode(RechargeRecordVo rechargeRecord, String cid, HttpServletRequest request) {
        //1.将指定毕设百度云地址给remark
        ContentVo contents = contentService.getContents(cid);
        rechargeRecord.setRemark(contents.getHref());
        //2.比对一下页面传入金额和数据库金额是否匹配
        if (rechargeRecord.getRechargeMoney().compareTo(contents.getPrice()) != 0) {
            return AjaxResult.error("不要搞事哦,我盯着你的呢！");
        }

        //3.此处获取当前会话的用户ID
        CnbsUserVo user = TaleUtils.getLoginCnbsUser(request);
        String orderNo = UUID.randomUUID().toString();
        rechargeRecord.setUserId(user == null ? "用户未登录" : user.getUid());
        rechargeRecord.setOrderNo(orderNo);
        rechargeRecord.setCreateTime(new Date());
        rechargeRecord.setRechargePoint(rechargeRecord.getRechargeMoney());

        //订单入库
        rechargeRecordService.save(rechargeRecord);
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                alipayConfig.getAppId(), alipayConfig.getPrivateKey(), "json", "GBK", alipayConfig.getPublicKey(), "RSA2");
        AlipayTradePrecreateRequest r = new AlipayTradePrecreateRequest();
        r.setBizContent("{" +
                "\"out_trade_no\":\"" + rechargeRecord.getOrderNo() + "\"," +
                "\"total_amount\":" + rechargeRecord.getRechargeMoney() + "," +
                "\"subject\":\"菜鸟毕设-源码支付\"" +
                "  }");
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(r);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (!response.isSuccess()) {
            return AjaxResult.error("调用支付宝接口生成二维码失败");
        }
        Map<String, Object> result = new HashMap<>(16);
        result.put("id", rechargeRecord.getOrderNo());
        result.put("qrCode", response.getQrCode());
        return AjaxResult.success(result);
    }

    /**
     * 查询支付结果
     *
     * @param outTradeNo
     * @return
     * @throws AlipayApiException
     */
    @PostMapping("/query/{outTradeNo}")
    @ResponseBody
    public AjaxResult queryPayState(@PathVariable String outTradeNo) throws AlipayApiException {
        boolean payState = alipayService.getPayState(outTradeNo, alipayConfig.getAppId(), alipayConfig.getPrivateKey(), alipayConfig.getPublicKey());
        return payState ? AjaxResult.success(1) : AjaxResult.error();
    }

    @GetMapping("/queryOrderInfo")
    @ResponseBody
    public R queryOrderInfo(String orderNo) {
        RechargeRecordVo rechargeRecordVo = rechargeRecordService.queryOrderInfo(orderNo);
        if (rechargeRecordVo == null) {
            return R.error("订单号输入错误！");
        }
        return R.ok().put("orderInfo", rechargeRecordVo);
    }
}
